import cgi
import os

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.api import images


class Message(db.Model):
  author = db.UserProperty()
  content = db.StringProperty(multiline=True)
  date = db.DateTimeProperty(auto_now_add=True)

class MainPage(webapp.RequestHandler):
  def get(self):
    messages_query = Message.all().order('-date')
    messages = messages_query.fetch(10)

    if users.get_current_user():
      logged_in = users.get_current_user()
      admin = users.is_current_user_admin()
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      logged_in = 'Nobody'
      admin = False
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'

    template_values = {
      'messages': messages,
      'url': url,
      'url_linktext': url_linktext,
      'logged_in':  logged_in,
      'admin':  admin,
      }

    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))
    

class DailyDiscussion(webapp.RequestHandler):
  def post(self):
    message = Message()
    if users.get_current_user():
      message.author = users.get_current_user()      
    message.content = self.request.get('content')
    message.put()
    self.redirect('/')

application = webapp.WSGIApplication([
  	('/', MainPage),
 	('/sign', DailyDiscussion)
], debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()